from .dsdiffdef import * 

def GetLogicChunk(ff):
	eof = False
	id3Exist = False
	try:
#		lHead = ff.read(12)
		id, size = struct.unpack("!4sQ",ff.read(12))
		print(id)
#		ff.seek(size, 1)
		if(id == b'ID3 '):
			id3Exist = True
		else:
			ff.seek(size, 1)
	except EOFError:
		eof = True

	return eof, id3Exist

def GetDSDIFFHeader(ff):
	buffersize = FormDSDChunkHeaderSize
	chunk=ff.read(buffersize)
	ivar = struct.unpack(FormDSDChunkHeaderFmt, chunk)

	id = ivar[0].to_bytes(4, byteorder="big", signed=False)
	dsd = ivar[2].to_bytes(4, byteorder="big", signed=False)

	if(id != b'FRM8' or dsd != b'DSD '):
		print("Ignore DSD header format error.")
		ivar = ""
	return ivar

def GetLogicChunkInfo(ff):
	try:
		ivar = struct.unpack(">IQ",ff.read(12))
	except EOFError:
		ivar = ""	
	return ivar

def FindDIINChunk(ff):
	offset = -1
	size = 0
	header_t = ""
	while(True):
		header_t = GetLogicChunkInfo(ff)
		id = header_t[0].to_bytes(4, byteorder="big", signed=False)
		if(id == b'DIIN'):
			offset = ff.tell() 
			print("Find a DIIN chunk, offset: ", offset)
			break
		else:
			ff.seek(header_t[1], 1)
	return header_t, offset

def FillDSDIFFHeader(ffout, head_t, fSize):
	buf = struct.pack(FormDSDChunkHeaderFmt, head_t[0], fSize, head_t[2])
	ffout.write(buf)

def modify_size_in_DSD_chunk(ffout, fileHead, diinHead):
	fSize = fileHead[1] - diinHead[1] - 12
	buf = struct.pack(FormDSDChunkHeaderFmt, fileHead[0], fSize, fileHead[2])
	ffout.write(buf)

def modify_size_in_PROP_chunk(ffout, fSize):
	print(fSize)
	buf = struct.pack("!Q", fSize)
	ffout.write(buf)

def CopyBytes(ffin, ffout, size):
	buf = ffin.read(size)
	ffout.write(buf)

def clear_diin_chunk():
	
	fin  = "../../temp/test.dff"
	fout = "../../temp/test_out.dff"
	
	ffin = open(fin, "rb")
	dsdHeader = GetDSDIFFHeader(ffin)

	if(dsdHeader==0):
		ffin.close()
		return False
	else:
		diinHeader, diinOffset = FindDIINChunk(ffin)

		if(diinOffset > 0):
			print(fin,", start clear DIIN chunk......")			
			ffout = open(fout, "wb")
			modify_size_in_DSD_chunk(ffout, dsdHeader, diinHeader)
			ffin.seek(FormDSDChunkHeaderSize)
			CopyBytes(ffin, ffout, diinOffset-FormDSDChunkHeaderSize-12)
			ffin.seek(diinHeader[1]+12, 1)
			CopyBytes(ffin, ffout, dsdHeader[1]-ffin.tell()+12)
			ffin.close()
			ffout.close()
			return True
		else:
			ffin.close()
			return False
